﻿using System.Reflection;
using System.Runtime.Loader;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using ZeroSum.App.Extensions;
using ZeroSum.App.Filters;

namespace ZeroSum.App;

/// <summary>
///     内部处理类
/// </summary>
internal static class InternalApp
{
    /// <summary>
    ///     初始化应用， 加载并过滤程序集等
    /// </summary>
    static InternalApp()
    {
        Assemblies = GetAssemblies();
    }

    public static IEnumerable<Assembly> Assemblies { get; }

    /// <summary>
    ///     扫描所有程序集， 过滤出项目程序集和框架程序集进行初始化
    /// </summary>
    /// <returns></returns>
    private static IEnumerable<Assembly> GetAssemblies()
    {
        var assemblies = DependencyContext.Default.RuntimeLibraries;
        return assemblies.Where(x =>
                x.Type == "project" ||
                x.Type == "package" && x.Name.StartsWith(nameof(ZeroSum))
            )
            .Select(x => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(x.Name)));
    }

    public static void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) =>
        {
            services.AddTransient<IStartupFilter, StartupFilter>();
            services.AddApp(context.Configuration);
        });
    }
}